# !/usr/bin/env python
# -*- coding:utf-8 -*-
# @FileName : p26.py
# @Time     : 2024/5/12 19:11
# @Author   : Robot-Zsj
"""
description:

跳马

https://fcqian.blog.csdn.net/article/details/134887408?spm=1001.2014.3001.5502

i:
3 5
47.48
4744.
7....

o:
17
"""
import sys

m, n = map(int, input().split())
grid = [input() for _ in range(m)]
stepGrid = [[0] * n for _ in range(m)]

reach = set()
for i in range(m):
    for j in range(n):
        reach.add(i * n + j)

offsets = ((1, 2), (1, -2), (2, 1), (2, -1), (-1, 2), (-1, -2), (-2, 1), (-2, -1))


def bfs(sx, sy, k):
    global reach

    queue = [(sx, sy, 0)]

    vis = set()
    vis.add(sx * n + sy)

    while len(queue) > 0 and k > 0:
        newQueue = []

        for x, y, step in queue:
            for offsetX, offsetY in offsets:
                newX = x + offsetX
                newY = y + offsetY

                pos = newX * n + newY
                if newX < 0 or newX >= m or newY < 0 or newY >= n or (pos in vis):
                    continue

                newQueue.append((newX, newY, step + 1))
                stepGrid[newX][newY] += step + 1
                vis.add(pos)
        queue = newQueue

        k -= 1
    reach &= vis


def getResult():
    for i in range(m):
        for j in range(n):
            if grid[i][j] != '.':
                k = int(grid[i][j])
                bfs(i, j, k)

    if len(reach) == 0:
        return -1

    minStep = sys.maxsize
    for pos in reach:
        x = pos // n
        y = pos % n
        minStep = min(minStep, stepGrid[x][y])
    return minStep


print(getResult())
